package com.adnaan.backend.controller.common;

import cn.dev33.satoken.annotation.SaIgnore;
import com.adnaan.backend.common.annotation.RestControllerMapping;
import com.adnaan.backend.common.model.Result;
import com.adnaan.backend.service.storage.StorageFactory;
import com.adnaan.backend.service.storage.StorageService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

/**
 * author: adnaan
 * create: 2025-01-17 15:09
 * Description:
 */
@Slf4j
@Tag(name = "上传文件")
@SaIgnore
@RestControllerMapping("/upload")
public class UploadController {
    private final StorageFactory storageFactory;

    public UploadController(StorageFactory storageFactory) {
        this.storageFactory = storageFactory;
    }

    @PostMapping
    @Operation(summary = "上传文件")
    public Result<Map<String, String>> upload(@RequestBody MultipartFile file) {
        if (file.isEmpty()) {
            return Result.error("上传文件为空");
        }
        try {
            StorageService storageService = storageFactory.getStorageService();
            String fileName = storageService.upload(file);
            Map<String, String> result = new HashMap<>();
            result.put("name", fileName);
            result.put("url", storageService.getUrl(fileName));
            return Result.success("文件上传成功", result);
        } catch (Exception e) {
            log.error("文件上传失败", e);
            return Result.error("文件上传失败：" + e.getMessage());
        }
    }
}
